﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridManager : MonoBehaviour
{
    public static GridManager instance;
    private List<Vector2> PointList= new List<Vector2>();//网格的位置
     
    private List<Grid> GridList = new List<Grid>();//网格的位置

    private void Awake()
    {
        CreatGrid();
        instance = this;
    }
    /// <summary>
    /// 生成网格坐标
    /// </summary>
    private void CreatGrid()
    {
        for(int index_x=0;index_x<9;index_x++)
        {
            for (int index_y=0;index_y<5;index_y++)
            {
                GridList.Add(new Grid(new Vector2(index_x,index_y),transform.position + new Vector3(index_x * 1.65f, 2 * index_y),false));
            }
        }
    }
    /// <summary>
    /// 获取网格坐标点
    /// </summary>
    public Vector2 GetGridPos()
    {
        
        return GetGridPos(Camera.main.ScreenToWorldPoint(Input.mousePosition));
    }
    /// <summary>
    /// 通过世界坐标获取
    /// </summary>
    /// <returns></returns>
    public Vector2 GetGridPos(Vector2 wordpos)
    {
        
        return GetGridByWordPos(wordpos).wordPoint;
    }
    private void Update()
    {
        if(Input.GetMouseButton(0))
        {
            Debug.Log(GetGridPos());
        }
    }
    public Grid GetGridByWordPos(Vector2 wordpos)
    {
        float dis = 1000;
        Grid pos = null ;
        for (int index = 0; index < GridList.Count; index++)
        {
            if (Vector2.Distance(wordpos, GridList[index].wordPoint) < dis)//格子有间隙
            {
                dis = Vector2.Distance(Camera.main.ScreenToWorldPoint(Input.mousePosition), GridList[index].wordPoint);
                pos = GridList[index] ;
            }
        }
        return pos;
    }
    /// <summary>
    /// 根据y轴寻找丧尸出生的位置
    /// </summary>
    /// <param name="vertical"></param>
    /// <returns></returns>
    public Grid GridByVertical(int vertical)
    {
        for(int index=0;index<GridList.Count;index++)
        {
            if (GridList[index].Point == new Vector2(8, vertical))
                return GridList[index];
        }
        return null;
    }
}
